package com.system.common.util;

import com.system.common.constant.BaseEnum;
import com.system.common.response.PageResp;

import java.util.Collections;

public class PageHelperUtil {

    /**
     * 每页记录数
     */
    public static final int DEFAULT_PAGE_SIZE = 20;

    public static final int DEFAULT_CURRENT_PAGE = 1;

    private PageHelperUtil() {
    }

    /**
     * 获得总页数
     *
     * @param totalRecord
     * @return
     */
    public static Integer getTotalPage(Integer totalRecord, Integer pageSize) {
        if (totalRecord == null || totalRecord == 0) {
            return 0;
        }
        if(pageSize == null || pageSize ==0){
            pageSize = DEFAULT_PAGE_SIZE;
        }
        //  总页数
        Integer totalPage = totalRecord / pageSize + (totalRecord % pageSize == 0 ? 0 : 1);
        return totalPage;
    }

    public static Integer getDefaultPageSize(Integer pageSize){
        if (pageSize == null || pageSize == 0) {
            return DEFAULT_PAGE_SIZE;
        }
        return pageSize;
    }

    public static Integer getDefaultCurrentPage(Integer currentPage){
        if (currentPage == null || currentPage == 0) {
            return DEFAULT_CURRENT_PAGE;
        }
        return currentPage;
    }

    /**
     * 获取偏移量
     *
     * @param totalRecord
     * @param currentPage
     * @return
     */
    public static Integer getOffset(Integer totalRecord, Integer currentPage, Integer pageSize) {
        if (totalRecord == null || totalRecord == 0) {
            return 0;
        }
        if (currentPage == null || currentPage == 0) {
            currentPage = DEFAULT_CURRENT_PAGE;
        }
        if (pageSize == null || pageSize == 0) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
        int offset = (currentPage - 1) * pageSize;
        if (offset < 0) {
            return 0;
        }
        return offset > totalRecord ? (getTotalPage(totalRecord, pageSize) - 1) * pageSize : offset;
    }

    /**
     * 获取默认分页对象
     *
     * @param <T>
     * @return
     */
    public static <T> PageResp<T> getDefaultPageHelper() {
        PageResp pageResp = new PageResp<T>();
        pageResp.setCode(BaseEnum.SUCCESS.getCode());
        pageResp.setCurrentPage(DEFAULT_CURRENT_PAGE);
        pageResp.setData(Collections.EMPTY_LIST);
        pageResp.setTotalPage(0);
        pageResp.setTotalRecord(0L);
        return pageResp;
    }

}
